#include "vgdb.h"

static void vgdb_init()
{
    vgdb()->state = VGDB_VGS_START;
    gdb_opto("\x1a\x1aprompt");
}

static void vgdb_run()
{
    while(vgdb()->state != VGDB_VGS_QUIT){
        vmsg_proc();
    }
}




/*********************************************************************************************************************/

/* 1. 尝试连接vim
 * 2. 尝试启动gdb
 * 3. 初始化并开始处理消息
**/
int vgdb_start(const char *args)
{
    pid_t   pid;
    int     rwfd;

    vim_init();
    gdb_init();
    switch(vim_connect()){
        case -5:
        case -4:
        case -3:
        case -2:
        case -1:
            DEBUG_MESSAGE("can not connetc to vim, exit now");
            return -2;
        default:
            switch(pid = forkpty(&rwfd,NULL,NULL,NULL)){
                case -1:
                    DEBUG_MESSAGE("forkpty() fail: %s", strerror(errno));
                    return -1;
                case 0:
                    gdb_start();
                    return 0;
                default:
                    gdb()->pid  = pid;
                    gdb()->rwfd = rwfd;
                    strcpy(gdb()->symfn, args);
                    vgdb_init();
                    vgdb_run();
                    return 0;
            }
    }
}


const char *vgdbstart(const char *args)
{
    switch(fork()){
        case -1:
            return "error: fork() failed";
        case 0:
            exit(vgdb_start(args));
            return "error: can not come here";
        default:
            return "ok: start vgdb process successfully";
    }
}

/*********************************************************************************************************************/
